<?php

namespace App\Listener;

use Hyperf\Consul\Agent;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Framework\Event\BootApplication;

use Hyperf\Di\Annotation\Inject;
use Hyperf\Contract\ConfigInterface;

use Hyperf\Consul\KV;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\Context\ApplicationContext;

#[Listener]
class ConsulServiceRegisterListener implements ListenerInterface
{
    #[Inject]
    protected ConfigInterface $config;
    public function listen(): array
    {
        return [BootApplication::class];
    }

    public function process(object $event): void
    {
        $consulConfig = $this->config->get('consul');
        $consulServer = $consulConfig['uri'];
        $container = ApplicationContext::getContainer();
        $clientFactory = $container->get(ClientFactory::class);
        $agent = new Agent(function () use ($clientFactory, $consulServer) {
            return $clientFactory->create([
                'base_uri' => $consulServer
            ]);
        });

        // 注册 HTTP 服务
        if ($consulConfig['services']['http']['enable']) {
            $http = $consulConfig['services']['http'];
            $agent->registerService([
                'Name' => $http['name'],
                'ID' => $http['id'],
                'Tags' => $http['tags'],
                'Address' => $http['address'],
                'Port' => $http['port'],
                'Check' => [
                    'HTTP' => $http['check']['http'],
                    'Interval' => $http['check']['interval'],
                    'Timeout' => $http['check']['timeout'],
                ],
            ]);
        }

        // 注册 RPC 服务
        if ($consulConfig['services']['rpc']['enable']) {
            $rpc = $consulConfig['services']['rpc'];
            $agent->registerService([
                'Name' => $rpc['name'],
                'ID' => $rpc['id'],
                'Tags' => $rpc['tags'],
                'Address' => $rpc['address'],
                'Port' => $rpc['port'],
                'Check' => [
                    'TCP' => $rpc['check']['tcp'],
                    'Interval' => $rpc['check']['interval'],
                    'Timeout' => $rpc['check']['timeout'],
                ],
            ]);
        }

        // 应用关闭时注销服务
        register_shutdown_function(function () use ($agent, $consulConfig) {
            if ($consulConfig['services']['http']['enable']) {
                $agent->deregisterService($consulConfig['services']['http']['id']);
            }
            if ($consulConfig['services']['rpc']['enable']) {
                $agent->deregisterService($consulConfig['services']['rpc']['id']);
            }
        });
    }
}
